<template>
  <div class="app-container customer-box">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form :inline="true" label-width="68px" style="margin-bottom: 15px;">
          <el-form-item label="客户名称">
            <el-input v-model="searchForm.name" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="searchForm.wContacts" clearable size="small" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <el-button v-hasPermi="['om:customer:query']" type="primary" icon="el-icon-search" @click="search">搜索
            </el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['om:customer:query']" type="primary" plain icon="el-icon-menu" size="mini"
              @click="checkleAll">查询所有</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" v-hasPermi="['om:customer:add']" plain icon="el-icon-plus" size="mini"
              @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['om:customer:Import']">导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['om:customer:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['om:customer:print']" plain icon="el-icon-s-platform" size="mini"
              @click="handlePrint">打印</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['om:customer:empty']" plain icon="el-icon-remove-outline" size="mini"
              @click="handleEmpty"  :disabled="customerData==0">清空</el-button>
          </el-col>
        </el-row>
        <!-- 客户数据 -->
        <el-table :data="customerData" border v-loading="loading" :height="maxHeight" :row-class-name="tableRowClassName">
          <el-table-column type="index" width="60" align="center" label="序号">
          </el-table-column>
          <el-table-column label="客户名称" align="center" prop="name" width="200">
          </el-table-column>
          <el-table-column label="简称" align="center" prop="shortName" width="100">
          </el-table-column>
          <el-table-column label="公司地址" align="center" prop="addr" width="300">
          </el-table-column>
          <el-table-column label="电话" align="center" prop="tel">
          </el-table-column>
          <el-table-column label="联系人" align="center" prop="wContacts" />
          <el-table-column label="手机号" align="center" prop="wMobile" />
          <el-table-column label="状态" align="center" key="status" width="100">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding" width="200">
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button size="mini" type="text" class="basic-see" @click.stop="handleSee(scope.row)">查看
                </el-button>
                <el-button size="mini" class="basic-update" v-hasPermi="['om:customer:edit']" type="text"
                  @click.stop="handleUpdate(scope.row)">修改
                </el-button>
                <el-button size="mini" v-hasPermi="['om:customer:remove']" style="color: #f56c6c;"
                  class="basic-delete" type="text" @click.stop="handleDelete(scope.row)">删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 打印数据 -->
        <PrintPage :printData="printData" ref="startPrint" />
      </el-col>
    </el-row>
    <!-- 分页信息 -->
    <pagination v-show="total>=21" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getCustomerlList" />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog title="客户" :visible.sync="open" width="600px" @close="close">
      <el-form ref="form" :model="customerForm" label-width="95px" :rules="rules" :disabled="butChange=='seeStatus'">
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="customerForm.name" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户别名">
              <el-input v-model="customerForm.alias" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="简称">
              <el-input v-model="customerForm.shortName" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属省/市">
              <el-cascader ref="classTree" :options="options" v-model="selectedOptions" @change="handleChangeCity"
                clearable>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公司地址">
              <el-input v-model="customerForm.addr" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮编">
              <el-input v-model="customerForm.postcode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input v-model="customerForm.tel" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用等级">
              <el-select v-model="customerForm.credit" placeholder="请选择">
                <el-option v-for="item in optionsTrust" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="信用额度">
              <el-input v-model="customerForm.creditLimit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户分类">
              <el-select v-model="customerForm.type" placeholder="请选择">
                <el-option v-for="item in optionsType" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="customerForm.remark" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="customerForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="Billing-box">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="开票信息" name="first">
              <el-row style="height: 164px;">
                <el-col :span="24">
                  <el-form-item label="开户行">
                    <el-input v-model="customerForm.bank" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="地址电话">
                    <el-input v-model="customerForm.addr2" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="账号">
                    <el-input v-model="customerForm.account" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="税号">
                    <el-input v-model="customerForm.tax" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="业务联系人" name="second">
              <el-row style="height: 164px;">
                <el-col :span="12">
                  <el-form-item label="联系人" label-width="60px">
                    <el-input v-model="customerForm.wContacts" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" label-width="60px">
                    <el-input v-model="customerForm.wMobile" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="财务联系人" name="third">
              <el-row style="height: 164px;">
                <el-col :span="12">
                  <el-form-item label="联系人" label-width="60px">
                    <el-input v-model="customerForm.fContacts" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" label-width="60px">
                    <el-input v-model="customerForm.fMobile" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="butChange!=='seeStatus'">
        <el-button type="primary" v-if="butChange=='addStatus'" @click="submitForm('form')">确定</el-button>
        <el-button type="success" v-if="butChange=='updateStatus'" @click="submitForm('form')">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 客户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的客户数据

        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCustomer,
    addCustomer,
    updateCustomer,
    delCustomer,
    exportCustomer,
    dictMatching,
    emptyFile
  } from "../../api/customer";
  import {
    isSerial
  } from "@/utils/cingsoft";
  import {
    provinceAndCityData
  } from 'element-china-area-data' //省市插件
  import PrintPage from "../../components/Customer/print"; //打印组件
  import {
    getToken
  } from "@/utils/auth";
  //并行请求
  import axios from 'axios';
  import print from "print-js"; //打印js
  export default {
    name: "Customer",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 客户查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 100,
          name: "",
          wContacts: ""
        },
        activeName: 'first',
        // 总条数
        total: 0,
        // 最大高度
        maxHeight: null,
        //客户数据
        customerData: [],
        //搜索参数
        searchForm: {
          name: "", //客户名称
          wContacts: "" //联系人
        },
        //分类
        optionsType: [],
        // 等级
        optionsTrust: [],
        // 省市
        options: provinceAndCityData,
        selectedOptions: [],
        // 客户导入参数
        upload: {
          // 是否显示弹出
          open: false,
          // 上传标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/om/customer/importData"
        },
        //打印数据
        printData: [],
        //打印状态
        printShow: false,
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        customerForm: {
          name: "",
          shortName: "",
          alias: "",
          addr: "",
          postcode: "",
          tel: "",
          bank: "",
          account: "",
          tax: "",
          addr2: "",
          cityId: "",
          credit: "",
          creditLimit: "",
          type: "",
          wMobile: "",
          wContacts: "",
          fMobile: "",
          fContacts: "",
          remark: "",
          status: "0"
        },
        //弹框提交按钮状态，1（新增） 2（修改）
        butChange: "",
        // 表单校验
        rules: {
          name: [{
            required: true,
            trigger: 'blur'
          }],
        }
      }
    },
    created() {
      //初始化客户档案
      this.getCustomerlList();
      //获取字典
      this.getDict();
    },
    methods: {
      // 获取客户数据
      getCustomerlList() {
        this.loading = true;
        listCustomer(this.queryParams).then(res => {
          if (res.code == 200) {
            this.loading = false;
            if (res.rows.length > 0) {
              let list = JSON.parse(JSON.stringify(res.rows));
              list.forEach((item, i) => {
                // let num = parseInt(i/5);
                if(i%5==0&&i!==0){
                  list[i-1].tag = 1
                }else{
                   list[i].tag = 0
                }
               this.customerData = list;
              })

            } else {
              this.customerData = [];
            }
            this.total = res.total;
            if (this.customerData.length >= 21) { //条数总数大于显示出现滚动条
              this.maxHeight = (`${document.documentElement.clientHeight}` - 270);
            } else {
              this.maxHeight = ""
            }
          }
        })
      },

      /* 字典类型 */
      getDict(type) {
        return new Promise((resolve, reject) => {
          const _self = this;
          //并行请求
          axios.all([
            // 客户类型
            dictMatching({
              dictType: "om_customer_type"
            }),
            //客户等级
            dictMatching({
              dictType: "om_customer_credit"
            }),

          ]).then(
            axios.spread(
              function(resType, resRrust) {
                if (resType.code == 200 && resRrust.code == 200) {
                  console.log(resType)
                  _self.optionsType = resType.rows;
                  _self.optionsTrust = resRrust.rows;
                  resolve()
                } else {
                  _self.msgError("获取信息失败")
                }
              }
            )
          )
        })
      },
      //搜索
      search() {
        this.queryParams.name = this.searchForm.name;
        this.queryParams.wContacts = this.searchForm.wContacts;
        this.getCustomerlList();
      },

      // 查询所有
      checkleAll() {
        //清空搜索信息，避免干扰
        this.searchForm.name = "";
        this.queryParams.name = "";
        this.searchForm.wContacts = "";
        this.queryParams.wContacts = "";
        this.getCustomerlList();
      },
      //供应商省市
      handleChangeCity(value) {
      },
      // 供应商tab签
      handleClick(tab, event) {
        console.log(tab, event);
      },
      // 客户状态修改
      handleStatusChange(row) {
        this.customerForm = Object.assign({}, row);
        let customer = this.customerForm;
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认' + text + '客户?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return updateCustomer(customer)
        }).then(() => {
          this.msgSuccess(text + "成功");
          this.reset();
          this.getCustomerlList();
        }).catch(function() {
          row.status = row.status === "0" ? "1" : "0";
          this.reset();
        });
      },

      // 新增客户信息
      handleAdd() {
        this.butChange = "addStatus";
        this.reset();
        this.open = true;
      },

      // 导入按钮操作
      handleImport() {
        this.upload.title = "客户信息导入";
        this.upload.open = true;
      },


      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },

      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", {
          dangerouslyUseHTMLString: true
        });
        this.getCustomerlList()
      },

      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },

      // 导出
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出客户档案?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportCustomer(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },

      // 打印
      handlePrint() {
        let number = 1;
        this.printData = this.customerData;
        this.printData.forEach(obj => {
          obj.id = number++
        })
        setTimeout(() => {
          this.$print(this.$refs.startPrint.$refs.print);
        }, 0)
      },

      //清空
    handleEmpty(){
      this.$confirm('是否确认清空客户档案?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return emptyFile();
      }).then(response => {
        this.getCustomerlList();
         this.msgSuccess("清空成功");
      })
    },
    // 间隔5行变色
    tableRowClassName({
      row,
      rowIndex
    }) {
      if (row.tag == 1) {
        return 'warning-row';
      }
    },
      // 查看客户信息
      handleSee(row) {
        this.customerForm = Object.assign({}, row); //拷贝物料信息
        this.butChange = "seeStatus";
        if (this.customerForm.cityId !== null && this.customerForm.cityId !== undefined) {
          this.selectedOptions = this.customerForm.cityId.split(",")
        } else {
          this.selectedOptions = [];
        }
        this.open = true;
      },

      // 修改客户信息
      handleUpdate(row) {
        this.customerForm = Object.assign({}, row); //拷贝物料信息
        this.butChange = "updateStatus";
        if (this.customerForm.cityId !== null && this.customerForm.cityId !== undefined) {
          this.selectedOptions = this.customerForm.cityId.split(",")
        } else {
          this.selectedOptions = [];
        };
        this.open = true;
      },

      // 提交新增客户档案表单
      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            if (this.butChange == "addStatus") {
              if (this.selectedOptions.length > 0) {
                this.options.forEach(item => {
                  if (this.selectedOptions[0] == item.value) {
                    this.customerForm.province = item.label;
                    item.children.forEach(v => {
                      if (this.selectedOptions[1] == v.value) {
                        this.customerForm.city = v.label;
                      }
                    })

                  }
                })
                this.customerForm.cityId = this.selectedOptions.join(",");
              } else {
                this.customerForm.cityId = "";
                this.customerForm.province = "";
                this.customerForm.city = "";
              }
              addCustomer(this.customerForm).then(res => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  this.getCustomerlList();
                  this.cancel()
                }
              }).catch(err => {
                this.msgError("新增失败");
              })
            } else {
              if (this.selectedOptions.length > 0) {
                this.options.forEach(item => {
                  if (this.selectedOptions[0] == item.value) {
                    this.customerForm.province = item.label;
                    item.children.forEach(v => {
                      if (this.selectedOptions[1] == v.value) {
                        this.customerForm.city = v.label;
                      }
                    })

                  }
                })

                this.customerForm.cityId = this.selectedOptions.join(",");


              } else {
                this.customerForm.cityId = "";
                this.customerForm.province = "";
                this.customerForm.city = "";
              }
              updateCustomer(this.customerForm).then(res => { //触发保存提交
                if (res.code == 200) {
                  this.getCustomerlList();
                  this.msgSuccess("修改成功");
                  this.open = false;
                }
              }).catch(err => {
                this.msgError("修改失败");
              })

            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      //删除客户
      handleDelete(row) {
        this.$confirm('确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return delCustomer(row.name);
        }).then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getCustomerlList();
            this.open = false;
          }
        })
      },

      /** 弹框取消 */
      cancel() {
        this.open = false;
        this.reset()
      },
      close() {
        this.reset()
      },

      /** 表单重置 */
      reset() {
        this.customerForm = {
          name: "",
          shortName: "",
          alias: "",
          addr: "",
          postcode: "",
          tel: "",
          bank: "",
          account: "",
          tax: "",
          addr2: "",
          city: "",
          cityId: "",
          credit: "",
          creditLimit: "",
          type: "",
          wMobile: "",
          wContacts: "",
          fMobile: "",
          fContacts: "",
          remark: "",
          status: "0"

        };
        this.resetForm("form");
        this.selectMaterials = [];
        this.selectedOptions = [];
        this.selectType = "";
        this.selectTrust = "";
        this.activeName = 'first';
        this.resetSelector();
        this.resetForm("form");
      },
      //解决级联选择器回显高亮异常问题
      resetSelector() {
        if (this.$refs.classTree) {
          this.$refs.classTree.$refs.panel.activePath = [];
          this.$refs.classTree.$refs.panel.calculateCheckedNodePaths();
        }
      },
    },
    components: {
      PrintPage
    }

  };
</script>
<style lang="scss">
  .customer-box {
    .el-tag.el-tag--info {
      color: #1890FF;
    }

    .el-table .warning-row {
      background-color: #F5F7FA;
    }
    .Billing-box {
      padding: 15px;
      box-shadow: 1px 1px 10px 1px #eee;
      border-radius: 5px;
      padding-bottom: 10px;
      margin: 10px 10px 0px 10px;

      h2 {
        font-size: 15px;
        font-weight: 700;
        margin: 0;
        border-bottom: 1px solid #dfe6ec;
        padding-bottom: 15px;
        margin-bottom: 15px;
      }
    }

    .el-switch {
      display: flex;
      justify-content: center;
    }

    .el-radio__input.is-disabled.is-checked .el-radio__inner {
      background-color: #F5F7FA;
      border-color: #999;
    }

    .el-radio {
      margin-right: 18px;
    }

    .el-radio__label {
      padding-left: 5px;
    }

    .el-radio:nth-of-type(3) {
      margin-right: 0;
    }

    .el-switch.is-disabled {
      opacity: 1;
    }

    .el-table .el-table__header-wrapper th,
    .el-table .el-table__fixed-header-wrapper th {
      height: 35px;
    }

    .el-dialog__body {
      padding-right: 15px;
      padding-bottom: 20px;

    }

    .el-input.is-disabled .el-input__inner {
      color: #333;
    }

    .el-form-item--medium .el-form-item__content {
      margin-right: 10px !important;
    }
  }

  .close-select {
    overflow: hidden;

    i {
      float: right;
      margin-right: 15px;
      color: #909399;
      cursor: pointer;
    }
  }
</style>
